<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="$t('user.levelConfig')"
    class="component-manage-level-add-or-update"
  >
    <el-tabs
      v-model="activeName"
      type="card"
    >
      <el-tab-pane
        :label="$t('user.generalConfiguration')"
        name="first"
      >
        <div class="prods-select-body">
          <!-- native modifier has been removed, please confirm whether the function has been affected  -->
          <el-form
            ref="dataFormRef"
            :model="dataForm"
            :label-width="$t('language')=== 'English'?'170px':'120px'"
            :rules="dataRule"
            @submit.prevent
          >
            <el-form-item
              :label="$t('user.levelNameCn')"
              prop="levelNameCn"
            >
              <el-input
                v-model="dataForm.levelNameCn"
                :placeholder="$t('user.enterGradeNameCn')"
                maxlength="10"
                style="width: 400px"
                show-word-limit
                type="text"
              />
            </el-form-item>
            <el-form-item
              :label="$t('user.levelNameEn')"
              prop="levelNameEn"
            >
              <el-input
                v-model="dataForm.levelNameEn"
                :placeholder="$t('user.enterGradeNameEn')"
                maxlength="10"
                style="width: 400px"
                show-word-limit
                type="text"
              />
            </el-form-item>
            <el-form-item
              :label="$t('user.bgImg')"
              prop="img"
            >
              <div>
                <img-upload
                  v-model="dataForm.img"
                />
                <div class="el-form-item-tips">
                  {{ $t("webInfoConfig.imgsTip") + '320*170' + $t("webInfoConfig.px") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.paidMemberPrice')"
              prop="needAmount"
            >
              <el-input
                v-model="dataForm.needAmount"
                :placeholder="$t('user.enterPrice')"
                type="number"
                min="0.01"
                style="width: 400px"
                oninput="if(value.length>10)value=value.slice(0,10)"
                step="0.0000001"
                @change="dataForm.needAmount = oninput(dataForm.needAmount)"
              >
                <template #append>
                  {{ $t("coupon.yuan") }}
                </template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.timeType')"
              prop="termType"
            >
              <el-radio-group v-model="dataForm.termType">
                <el-radio :label="1">
                  {{ $t("coupon.day") }}
                </el-radio>
                <el-radio :label="2">
                  {{ $t("user.week") }}
                </el-radio>
                <el-radio :label="3">
                  {{ $t("user.month") }}
                </el-radio>
                <el-radio :label="4">
                  {{ $t("user.season") }}
                </el-radio>
                <el-radio :label="5">
                  {{ $t("user.year") }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              :label="$t('user.requiredGrowthValue')"
              prop="needGrowth"
            >
              <el-input
                v-model="dataForm.needGrowth"
                :placeholder="$t('user.enterInteger')"
                type="number"
                style="width: 400px"
                :min="minNeedGrowth"
                :max="maxNeedGrowth"
                precision="0"
                :disabled="dataForm.level === 1 && dataForm.levelType === 0"
                @blur="onChangeNeedGrowth()"
              >
                <template #append>
                  {{ $t("user.growth") }}
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('user.equityAllocation')"
        name="third"
      >
        <div class="prods-select-body">
          <!-- native modifier has been removed, please confirm whether the function has been affected  -->
          <el-form
            label-width="30px"
            @submit.prevent
          >
            <el-form-item prop="isFreeFee">
              <el-checkbox v-model="isFreeFee">
                {{
                  userRightsList[1] ? userRightsList[1].rightsName : ''
                }}
              </el-checkbox>
            </el-form-item>
            <el-form-item prop="rateScore">
              <el-checkbox v-model="isRateScore">
                {{
                  userRightsList[4] ? userRightsList[4].rightsName : ''
                }}
              </el-checkbox>
              <el-input-number
                v-if="isRateScore"
                v-model="dataForm.rateScore"
                :placeholder="$t('user.enterMagnification')"
                :min="1"
                :max="100"
                :precision="2"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item prop="couponList">
              <el-checkbox v-model="isCoupon">
                {{
                  userRightsList[3] ? userRightsList[3].rightsName : ''
                }}
              </el-checkbox>
              <template v-if="isCoupon">
                <span style="margin: 0 20px">
                  <!-- native modifier has been removed, please confirm whether the function has been affected  -->
                  <el-button
                    type="primary"
                    text
                    @click.prevent="onConpouSelectHandle()"
                  >{{ $t("user.selectCoupons") }}</el-button>
                </span>
                <span
                  v-for="(item, index) in dataForm.couponList"
                  :key="index"
                >
                  <span v-if="index < 2">{{ item.couponName
                  }}{{
                    index == 1 && dataForm.couponList.length > 2
                      ? $t("user.etcCoupons")
                      : ""
                  }}</span>
                  &nbsp;
                </span>
              </template>
            </el-form-item>
            <el-form-item prop="presScore">
              <el-checkbox v-model="isPresScore">
                {{
                  userRightsList[2] ? userRightsList[2].rightsName : ''
                }}
              </el-checkbox>
              <el-input-number
                v-if="isPresScore"
                v-model="dataForm.presScore"
                :placeholder="$t('user.enterInteger')"
                :min="0"
                :max="100000000"
                :precision="0"
                controls-position="right"
              >
                <template #append>
                  {{ $t("order.score") }}
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item prop="discount">
              <el-checkbox v-model="isDiscount">
                {{
                  userRightsList[0] ? userRightsList[0].rightsName : ''
                }}
              </el-checkbox>
              <el-input-number
                v-if="isDiscount"
                v-model="dataForm.discount"
                :placeholder="$t('user.discountRange')"
                :min="0.01"
                :max="10"
                :precision="2"
                style="width: 160px;"
                controls-position="right"
              >
                <template #append>
                  {{ $t("marketing.fold") }}
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item
              v-if="isDiscount"
              prop="discountRange"
              class="discount-body"
            >
              <el-radio-group v-model="dataForm.discountRange">
                <el-radio :label="0">
                  {{ $t("user.platform") }}
                </el-radio>
                <el-radio :label="1">
                  {{ $t("user.selfShop") }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              prop="discountType"
              class="discount-body"
            >
              <el-radio-group
                v-if="isDiscount"
                v-model="dataForm.discountType"
              >
                <el-radio :label="0">
                  {{ $t("user.allProducts") }}
                </el-radio>
                <el-radio :label="1">
                  {{ $t("user.categoryGoods") }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="isDiscount && dataForm.discountType === 1"
              prop="categorys"
            >
              <el-tree
                ref="categoryTreeRef"
                :data="categoryList"
                :props="categoryListTreeProps"
                node-key="categoryId"
                show-checkbox
              />
            </el-form-item>
            <el-form-item prop="presScore">
              <el-form-item prop="discountRange">
                <div>
                  <el-checkbox v-model="isOrther">
                    {{
                      $t("user.otherRights")
                    }}
                  </el-checkbox>
                  <el-checkbox-group
                    v-if="isOrther"
                    v-model="userRightsIds"
                    @change="onCheckbox"
                  >
                    <el-checkbox
                      v-for="item in rightsDataList"
                      :key="item.rightsId"
                      style="margin:4px 30px 0 0"
                      :label="item.rightsId"
                      border
                    >
                      {{ item.rightsName }}
                    </el-checkbox>
                  </el-checkbox-group>
                  <div
                    style="color:red;"
                    class="disabled-btn text-btn default-btn"
                  >
                    {{ $t("marketing.discountTip2") }}
                  </div>
                </div>
              </el-form-item>
            </el-form-item>
          </el-form>
          <coupon-select
            v-if="couponSelectVisible"
            ref="couponSelectRef"
            :get-way="1"
            @refresh-select-coupon-list="onSelectDistributionCoupon"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("coupon.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmitProds()"
        >
          {{ $t("coupon.confirm") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate } from '@/utils'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const couponSelectVisible = ref(false)
const activeName = ref('first')
const dataForm = ref({
  id: null,
  level: 0,
  levelNameCn: '',
  levelNameEn: '',
  levelType: 0,
  needGrowth: 0,
  needAmount: 0,
  term: 1,
  termType: 1,
  img: '',
  discount: 10,
  discountRange: 0,
  discountType: 0,
  presScore: 0,
  rateScore: 1,
  isFreeFee: 0,
  couponList: [],
  userRightsIds: [],
  categoryList: [],
  categorys: []
})
const isRateScore = ref(false)
const isFreeFee = ref(false)
const isCoupon = ref(false)
const isPresScore = ref(false)
const isDiscount = ref(false)
const isOrther = ref(false)
const minNeedGrowth = ref(null)
const maxNeedGrowth = ref(null)
const userRightsIds = ref([])
const rightsDataList = ref([])
const categoryList = ref([])
const userRightsList = ref([])
const categoryListTreeProps = reactive({
  label: 'categoryName',
  children: 'children'
})
// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  const reg = /^[1-9]\d*$/
  if (!reg.test(dataForm.value.term)) {
    callback(new Error($t('user.integerGreaterThanZero')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateNeedGrowth = (rule, value, callback) => {
  const num = setNumber(dataForm.value.needGrowth)
  if (maxNeedGrowth.value) {
    if (num > maxNeedGrowth.value) {
      dataForm.value.needGrowth = maxNeedGrowth.value
      callback(new Error($t('user.requiredGrowthValueMaximum')))
    }
  }
  if (num < minNeedGrowth.value) {
    callback(new Error($t('user.requiredGrowthValueMinimum')))
  } else {
    callback()
  }
}
const dataRule = {
  levelNameCn: [
    { required: true, message: $t('user.gradeNmaeCannotEmptyCn'), trigger: 'blur' }
  ],
  img: [
    { required: true, message: $t('user.bgImgCannotEmpty'), trigger: 'blur' }
  ],
  term: [
    { required: true, validator: validateTime, trigger: 'blur' }
  ],
  needGrowth: [
    { required: true, validator: validateNeedGrowth, trigger: 'blur' }
  ]
}
const categoryTreeRef = ref(null)
let isSubmit
let msg = ''
let isCheckSccuss

onActivated(() => {
  getDataList()
})

// 获取数据列表
const dataFormRef = ref(null)
const init = (userLevels, index) => {
  userLevels = JSON.parse(JSON.stringify(userLevels))
  // 初始化
  visible.value = true
  activeName.value = 'first'
  isRateScore.value = false
  isFreeFee.value = false
  isCoupon.value = false
  isPresScore.value = false
  isDiscount.value = false
  isOrther.value = false
  isSubmit = true
  categoryList.value = []
  if (userLevels[index].id) {
    getDataList(userLevels, index)
  } else {
    // 保存直接写入数据
    dataForm.value = userLevels[index]

    const lang = localStorage.getItem('bbcLang') || 'zh_CN'

    {
      const levelName = lang === 'zh_CN' ? 'dataForm.levelNameCn' : 'dataForm.levelNameEn'
      if (levelName === 'dataForm.levelNameEn' && !levelName) {
        dataForm.value.levelName = dataForm.value.levelNameCn
      } else {
        dataForm.value.levelName = levelName
      }
    }

    userRightsIds.value = dataForm.value.userRightsIds
    // 设置所需积分最大最小值
    serMinOrMaxNeedGrowth(userLevels, index)
    getCategoryDataList()
    getRightsDataList()
    getUserRightsList()
  }
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}
defineExpose({ init })
/**
 * 获取初始话数据
 */
const getDataList = (userLevels, index) => {
  http({
    url: http.adornUrl('/user/userLevel/info/' + parseInt(userLevels[index].id)),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data?.userLevelLangList) {
      data.userLevelLangList.map(val => {
        const levelName = ['levelNameCn', 'levelNameEn'][val.lang]
        data[levelName] = val.levelName
        return val
      })
    }
    dataForm.value = data
    userRightsIds.value = data.userRightsIds
    setRightsStatus(data)
    serMinOrMaxNeedGrowth(userLevels, index)
    getCategoryDataList()
    getRightsDataList()
    getUserRightsList()
  })
}
/**
 * 获取商品分类列表
 */
const getCategoryDataList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2
    })
  }).then(({ data }) => {
    const _categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
    _categoryList.forEach(item1 => {
      let t = false
      if (item1.children && item1.children.length > 0) {
        item1.children.forEach(item2 => {
          if (item2.children && item2.children.length > 0) {
            t = true
          }
        })
      }
      if (t) {
        categoryList.value.push(item1)
      }
    })
    if (dataForm.value.discountType === 1) {
      nextTick(() => {
        categoryTreeRef.value?.setCheckedKeys(dataForm.value.categorys)
      })
    }
  })
}

/**
 * 获取系统权益列表
 */
const getUserRightsList = () => {
  http({
    url: http.adornUrl('/user/userRights'),
    method: 'get',
    params: http.adornParams(
      {
        current: 1,
        size: 5,
        serviceType: 0
      }
    )
  }).then(({ data }) => {
    const lang = localStorage.getItem('bbcLang') || 'zh_CN'
    data.records.map(element => {
      let rightsNameCn, rightsNameEn
      if (!element.userRightsLangList) return element
      element.userRightsLangList.map(val => {
        if (val.lang === 0) {
          rightsNameCn = val.rightsName
        }
        if (val.lang === 1) {
          rightsNameEn = val.rightsName
        }
        return val
      })
      element.rightsName = lang === 'zh_CN' ? rightsNameCn : rightsNameEn || rightsNameCn
      return element
    })
    userRightsList.value = data.records.sort((a, b) => {
      return a.rightsId - b.rightsId
    })
  })
}
/**
 * 获取用户权益列表
 */
const getRightsDataList = () => {
  http({
    url: http.adornUrl('/user/userRights/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    const lang = localStorage.getItem('bbcLang') || 'zh_CN'
    data.map(element => {
      let rightsNameCn, rightsNameEn
      if (!element.userRightsLangList) return element
      element.userRightsLangList.map(val => {
        if (val.lang === 0)rightsNameCn = val.rightsName
        if (val.lang === 1)rightsNameEn = val.rightsName
        return val
      })
      element.rightsName = lang === 'zh_CN' ? rightsNameCn : rightsNameEn || rightsNameCn
      return element
    })
    rightsDataList.value = data
  })
}
/**
 * 设置所需积分最大最小值
 */
const serMinOrMaxNeedGrowth = (userLevels, index) => {
  if (userLevels[index].level > 1) {
    minNeedGrowth.value = userLevels[index - 1].needGrowth === 1000000000 ? userLevels[index - 1].needGrowth : userLevels[index - 1].needGrowth + 1
  } else {
    minNeedGrowth.value = 0
  }
  if (index < userLevels.length - 1 && userLevels[index + 1].needGrowth !== 0) {
    maxNeedGrowth.value = userLevels[index + 1].needGrowth - 1
  } else {
    maxNeedGrowth.value = 1000000000
  }
}
/**
 * 显示添加指定优惠券弹框
 */
const couponSelectRef = ref(null)
const onConpouSelectHandle = () => {
  couponSelectVisible.value = true
  nextTick(() => {
    couponSelectRef.value.init(dataForm.value.couponList)
  })
}
/**
 * 优惠券选择回调
 */
const onSelectDistributionCoupon = (coupons) => {
  if (coupons.length > 0) {
    dataForm.value.couponList = coupons
  } else {
    dataForm.value.couponList = []
    isCoupon.value = false
  }
}
/**
 * 权益选项数据校验
 */
const setRights = () => {
  // 邮费
  if (isFreeFee.value) {
    dataForm.value.isFreeFee = 1
  } else {
    dataForm.value.isFreeFee = 0
  }
  // 折扣
  if (!isDiscount.value) {
    dataForm.value.discount = 10
    dataForm.value.discountRange = 0
    dataForm.value.discountType = 0
  }
  // 优惠券
  if (!isCoupon.value) {
    dataForm.value.couponList = []
  }
  // 积分倍率
  if (!isRateScore.value) {
    dataForm.value.rateScore = 1
  }
  // 赠送积分
  if (!isPresScore.value) {
    dataForm.value.presScore = 0
  }
  // 其他权益
  if (!isOrther.value) {
    dataForm.value.userRightsIds = []
  } else {
    dataForm.value.userRightsIds = userRightsIds.value
  }
}
const checkData = () => {
  if (!dataForm.value.img) {
    msg = $t('user.bgImgCannotEmpty')
    isCheckSccuss = false
    return false
  }
  if (isDiscount.value) {
    if (dataForm.value.discountType === 1 && categoryTreeRef.value.getCheckedKeys().length === 0) {
      msg = $t('user.selectCategory')
      isCheckSccuss = false
      return false
    }
  }
  if (dataForm.value.levelNameCn.length < 1 || !dataForm.value.levelNameCn.trim()) {
    msg = $t('user.gradeNmaeCannotEmptyCn')
    isCheckSccuss = false
    return false
  }
  // 积分倍率
  if (isRateScore.value) {
    if (!dataForm.value.rateScore) {
      msg = $t('user.enterMagnification')
      isCheckSccuss = false
      return false
    } else if (dataForm.value.rateScore === 1) {
      msg = $t('user.feedback1')
      isCheckSccuss = false
      return false
    }
  }
  // 优惠券
  if (isCoupon.value && dataForm.value.couponList.length < 1) {
    msg = $t('user.selectCoupons')
    isCheckSccuss = false
    return false
  }
  // 赠送积分
  if (isPresScore.value && !dataForm.value.presScore) {
    msg = $t('user.bonus0')
    isCheckSccuss = false
    return false
  }
  // 折扣
  if (isDiscount.value) {
    if (!dataForm.value.discount) {
      msg = $t('user.discountRange')
      isCheckSccuss = false
      return false
    } else if (dataForm.value.discount === 10) {
      msg = $t('user.discountRangeValue')
      isCheckSccuss = false
      return false
    }
  }
}
/**
 * 确定事件
 */
const onSubmitProds = () => {
  if (!isSubmit) {
    return
  }
  // 校验数据
  isCheckSccuss = true
  checkData()
  if (!isCheckSccuss) {
    errorMsg(msg)
    return
  }
  // 数据校验
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    isSubmit = false
    // 根据数据设置权限
    setRights()
    if (dataForm.value.discountType === 1) {
      dataForm.value.categorys = categoryTreeRef.value?.getCheckedKeys()
    }
    if (!isDiscount.value || !dataForm.value.discountType) {
      dataForm.value.categorys = null
    }
    if (dataForm.value.userLevelLangList) {
      dataForm.value.userLevelLangList.map((val) => {
        if (val.lang === 0)val.levelName = dataForm.value.levelNameCn
        if (val.lang === 1)val.levelName = dataForm.value.levelNameEn
        return val
      })
    } else {
      dataForm.value.userLevelLangList = [
        {
          lang: 0,
          levelName: dataForm.value.levelNameCn
        },
        {
          lang: 1,
          levelName: dataForm.value.levelNameEn
        }
      ]
    }

    http({
      url: http.adornUrl('/user/userLevel'),
      method: 'put',
      data: http.adornData(dataForm.value)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500
      })
      emit('refreshDataList')
    }).catch(() => { })
    dataForm.value = {}
    visible.value = false
  })
}
const setRightsStatus = (data) => {
  data.isFreeFee === 0 ? isFreeFee.value = false : isFreeFee.value = true
  data.discount === 10 ? isDiscount.value = false : isDiscount.value = true
  data.rateScore === 1 ? isRateScore.value = false : isRateScore.value = true
  data.presScore === 0 ? isPresScore.value = false : isPresScore.value = true
  data.couponList.length < 1 ? isCoupon.value = false : isCoupon.value = true
  data.userRightsIds.length < 1 ? isOrther.value = false : isOrther.value = true
}
/**
 * 所需成长值数据变化校验
 */
const onChangeNeedGrowth = () => {
  let num = dataForm.value.needGrowth
  num = Number(num).toFixed(0)
  num = Number(num.toString().replace(/[^\d]/g, ''))
  dataForm.value.needGrowth = num
}
const oninput = (needAmount) => {
  let amount = parseFloat(needAmount)
  if (isNaN(amount)) {
    // errorMsg($t('marketing.pleaseThan0'))
    return 0.01
  }
  amount = +Number(needAmount).toFixed(2)
  if (amount === 0) {
    amount = 0.01
  }
  let cur = amount.toString()
  let reString = cur.indexOf('.')
  if (reString < 0) {
    reString = cur.length
    cur += '.'
  }
  while (cur.length <= reString + 2) {
    cur += '0'
  }
  if (parseFloat(needAmount) < 0) {
    return 0.01
  }
  return parseFloat(cur).toFixed(2)
}

/**
 * 权益多选时触发事件
 */
const onCheckbox = () => {
  // if (value.length < 1) {
  //   isOrther.value = false
  // }
}
/**
 * 判断数据
 */
const setNumber = (value) => {
  const num = Math.round(value)
  if (num < 0) {
    return 0
  } else {
    return num
  }
}
/**
 * 错误提示框
 */
const errorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}

</script>
<style scoped lang="scss">
.component-manage-level-add-or-update{
  .prods-select-body {
    height: 500px;
    overflow: auto;
  }
  .discount-body {
    margin-left: 30px;
    overflow: auto;
  }
  .el-form-item-tips {
    width: 100%;
  }
}

</style>
